/**
 * 用户状态管理
 * 用于管理当前登录用户的memberId等信息
 */

// 用户信息存储键名
const USER_INFO_KEY = 'userInfo';
const CURRENT_MEMBER_ID_KEY = 'currentMemberId';

/**
 * 获取当前用户的memberId
 * @returns {number|null} 当前用户的memberId，如果未登录则返回null
 */
export function getCurrentMemberId() {
	// 优先从本地存储获取
	const userInfo = uni.getStorageSync(USER_INFO_KEY);
	if (userInfo && userInfo.memberId) {
		const memberId = parseInt(userInfo.memberId);
		console.log('从userInfo获取到memberId:', userInfo.memberId, '转换为数字:', memberId);
		return memberId;
	}
	
	// 从本地存储获取memberId
	const memberId = uni.getStorageSync(CURRENT_MEMBER_ID_KEY);
	if (memberId) {
		const numMemberId = parseInt(memberId);
		console.log('从currentMemberId获取到memberId:', memberId, '转换为数字:', numMemberId);
		return numMemberId;
	}
	
	console.log('未找到用户memberId');
	return null;
}

/**
 * 设置当前用户的memberId
 * @param {number|string} memberId 用户ID
 */
export function setCurrentMemberId(memberId) {
	if (memberId) {
		// 确保存储的是字符串类型，保持一致性
		const memberIdStr = String(memberId);
		uni.setStorageSync(CURRENT_MEMBER_ID_KEY, memberIdStr);
		console.log('设置当前用户memberId:', memberId, '存储为字符串:', memberIdStr);
	}
}

/**
 * 设置用户信息
 * @param {object} userInfo 用户信息对象
 */
export function setUserInfo(userInfo) {
	if (userInfo && userInfo.memberId) {
		// 确保memberId是字符串类型
		const memberIdStr = String(userInfo.memberId);
		userInfo.memberId = memberIdStr;
		
		uni.setStorageSync(USER_INFO_KEY, userInfo);
		uni.setStorageSync(CURRENT_MEMBER_ID_KEY, memberIdStr);
		console.log('设置用户信息:', userInfo);
		console.log('memberId已转换为字符串:', memberIdStr);
	}
}

/**
 * 获取用户信息
 * @returns {object|null} 用户信息对象
 */
export function getUserInfo() {
	return uni.getStorageSync(USER_INFO_KEY);
}

/**
 * 清除用户信息
 */
export function clearUserInfo() {
	uni.removeStorageSync(USER_INFO_KEY);
	uni.removeStorageSync(CURRENT_MEMBER_ID_KEY);
	console.log('清除用户信息');
}

/**
 * 检查用户是否已登录
 * @returns {boolean} 是否已登录
 */
export function isLoggedIn() {
	return getCurrentMemberId() !== null;
}

/**
 * 从地址列表中获取memberId（用于初始化）
 * @param {Array} addressList 地址列表
 * @returns {number|null} memberId
 */
export function getMemberIdFromAddressList(addressList) {
	if (addressList && addressList.length > 0) {
		const memberId = addressList[0].memberId;
		if (memberId) {
			const numMemberId = parseInt(memberId);
			setCurrentMemberId(numMemberId);
			console.log('从地址列表获取到memberId:', memberId, '转换为数字:', numMemberId);
			return numMemberId;
		}
	}
	return null;
}

/**
 * 从购物车列表中获取memberId（用于初始化）
 * @param {Array} cartList 购物车列表
 * @returns {number|null} memberId
 */
export function getMemberIdFromCartList(cartList) {
	if (cartList && cartList.length > 0) {
		const memberId = cartList[0].memberId;
		if (memberId) {
			const numMemberId = parseInt(memberId);
			setCurrentMemberId(numMemberId);
			console.log('从购物车列表获取到memberId:', memberId, '转换为数字:', numMemberId);
			return numMemberId;
		}
	}
	return null;
} 